package com.xdjd.mobile.business.service;

import com.alibaba.fastjson.JSON;
import com.gitee.easyopen.ApiContext;
import com.gitee.easyopen.session.SessionManager;
import com.xdjd.mobile.business.constant.Constant;
import com.xdjd.mobile.business.constant.IsOwnStatus;
import com.xdjd.mobile.business.dao.daoservice.activity.ActivityChallengeRecordDetailPoService;
import com.xdjd.mobile.business.dao.daoservice.activity.ActivityChallengeRecordPoService;
import com.xdjd.mobile.business.dao.daoservice.member.MemberUserPoService;
import com.xdjd.mobile.business.dao.daoservice.member.MemberUserStepPoService;
import com.xdjd.mobile.business.dao.daoservice.member.MemberUserWalletPoService;
import com.xdjd.mobile.business.entity.model.activity.ActivityChallengeRecordDetailPo;
import com.xdjd.mobile.business.entity.model.activity.ActivityChallengeRecordPo;
import com.xdjd.mobile.business.entity.model.member.MemberUserPo;
import com.xdjd.mobile.business.entity.model.member.MemberUserStepPo;
import com.xdjd.mobile.business.entity.model.member.MemberUserWalletPo;
import com.xdjd.mobile.business.entity.param.my.LoginParam;
import com.xdjd.mobile.business.entity.vo.LoginUser;
import com.xdjd.mobile.business.util.DateUtil;
import com.xdjd.mobile.business.util.UUIDUtil;
import com.xdjd.mobile.business.util.UUIDUtils;
import com.xdjd.mobile.business.util.UserLogoUtil;
import com.xdjd.mobile.system.exception.IphoneException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Random;

/**
 * Created by Administrator on 2019/1/9 0009.
 */
@Service
public class LoginService {
    private static final Logger logger = LoggerFactory.getLogger(LoginService.class);
    @Autowired
    private RedisTemplate<String, String> template;
    @Autowired
    private MemberUserPoService memberUserPoService;
    @Autowired
    private MemberUserWalletPoService memberUserWalletPoService;
    @Autowired
    private MemberUserStepPoService memberUserStepPoService;
    @Autowired
    private ActivityChallengeRecordPoService activityChallengeRecordPoService;
    @Autowired
    private ActivityChallengeRecordDetailPoService activityChallengeRecordDetailPoService;

    public MemberUserPo addUser2Redis(MemberUserPo user) {
        SessionManager sessionManager = ApiContext.getApiConfig().getSessionManager();
        HttpSession oldSession = sessionManager.getSession(user.getAccessToken());
        oldSession.invalidate();
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user, loginUser);
        HttpSession session = sessionManager.getSession(null);
        session.setAttribute("xdjd-user", JSON.toJSONString(loginUser));
        user.setAccessToken(session.getId());
        memberUserPoService.updateMember(user);
        return user;
    }

    public boolean checkVerifyCode(String mobile, String smsCode) {
        String bizType = "10";
        String smsCodeKey = bizType + ":" + mobile;
        String smsCodeFromRedis = template.opsForValue().get(smsCodeKey);
        if (null == smsCodeFromRedis) {
            logger.error("未查询到与当前设备和业务关联的验证码，验证失败。");
            return false;
        }
        return smsCodeFromRedis.equalsIgnoreCase(smsCode);
    }

    /**
     * 校验用户是否存在,不存在则注册
     */
    @Transactional
    public MemberUserPo isExistLoginUser(LoginParam loginParam) {
        MemberUserPo memberPo = memberUserPoService.getMemberByAccount(loginParam.getUserName());
        // 校验用户是否存在,不存在则注册
        if (null == memberPo) {
            memberPo = new MemberUserPo();
            memberPo.setAccount(loginParam.getUserName());
            memberPo.setImage(UserLogoUtil.getDefaultLogo());
            memberPo.setNickName(Constant.DEFAULT_NICKNAME + (new Random().nextInt(9000) + 1000));
            memberPo.setGender((byte) 0);
            memberPo.setSource(loginParam.getSource());
            memberPo.setDevice(loginParam.getDevice());
            memberPo.setSignature(Constant.DEFAULT_SIGNATURE);
            memberPo.setInviteCode(UUIDUtils.getInviteCode(Long.valueOf(loginParam.getUserName())));
            // 添加用户
            memberUserPoService.saveMember(memberPo);
            MemberUserWalletPo memberUserWalletPo = new MemberUserWalletPo();
            memberUserWalletPo.setMemberId(memberPo.getId());
            memberUserWalletPo.setBalance(0l);
            memberUserWalletPo.setGoldCoins(0l);
            memberUserWalletPo.setTotalIncome(0l);
            memberUserWalletPo.setFreezeFunds(0l);
            memberUserWalletPo.setObtainCoin(0);
            memberUserWalletPoService.saveWallet(memberUserWalletPo);
            MemberUserStepPo memberUserStepPo = new MemberUserStepPo();
            memberUserStepPo.setMemberId(memberPo.getId());
            memberUserStepPo.setTodayStepNumber(loginParam.getStepNumber());
            memberUserStepPo.setExchangeChallengeCount(0);
            memberUserStepPo.setChallengeCount(0);
            memberUserStepPo.setTotalStepNumber(0l);
            memberUserStepPo.setIsGet(new Byte("0"));
            if (loginParam.getStepNumber().longValue() >= Constant.CHANCE_STEP.longValue()) {
                memberUserStepPo.setChallengeCount(1);
                memberUserStepPo.setIsGet(new Byte("1"));
            }
            memberUserStepPoService.saveUserStep(memberUserStepPo);
            if (loginParam.getStepNumber() != null && loginParam.getStepNumber().longValue() >= Constant.CHANCE_STEP.longValue()) {
                memberUserStepPoService.addChanceCountLock(memberPo.getId());
                ActivityChallengeRecordPo recordPo = new ActivityChallengeRecordPo();
                recordPo.setMemberId(memberPo.getId());
                recordPo.setRecordNo("XD" + UUIDUtil.createOutTradeNo());
                recordPo.setChallengeCount(0);
                recordPo.setStepNumber(loginParam.getStepNumber());
                recordPo.setRecordDate(new Date());
                recordPo.setCompleteStatus(new Byte("0"));
                recordPo.setObtainCoin(0);
                activityChallengeRecordPoService.saveRecord(recordPo);
                ActivityChallengeRecordDetailPo detailPo = new ActivityChallengeRecordDetailPo();
                detailPo.setRecordNo(recordPo.getRecordNo());
                detailPo.setMemberId(memberPo.getId());
                detailPo.setStepNumber(loginParam.getStepNumber());
                detailPo.setRecordDate(new Date());
                detailPo.setIsOwn(IsOwnStatus.is_own.getCode().byteValue());
                detailPo.setObtainCoin(0);
                activityChallengeRecordDetailPoService.saveRecordDetail(detailPo);
            }
        }
        return memberPo;
    }
}
